#!/bin/sh
export LANG="zh_CN.UTF-8"

# start or stop or restart
optype=$1

# 进程名称, 修改此处
PROGNAME='mysql-5.7.37'

if [ x"${optype}" = x ] ; then
    optype=start
fi

#检查程序是否在运行
function exist()
{
	  # 进程数量
    prog_num=`ps -ef | grep $PROGNAME | grep -v 'grep' | grep -v 'bash -c' | wc -l`
    return $prog_num
}


#启动程序
function start()
{
    exist
    if [ $? -eq 0 ] ; then
        mysqld --defaults-file=/app/icstest/mysql-5.7.37/my.cnf --user=icstest &
		    echo "$PROGNAME is starting, please waiting"
		    sleep 5
		    exist
		    if [ $? -eq 0 ]; then
            echo "【WARN】$PROGNAME is start fail"
        else
            echo "$PROGNAME is started"
        fi
    else
        echo "$PROGNAME is started"
    fi
}


#关闭程序
function stop()
{
    exist
    if [ $? -eq 0 ] ; then
      echo "$PROGNAME is stopped"
      return
    fi
    
    # 查出所有进程 id
    pids=`ps -ef | grep $PROGNAME | grep -v 'grep' | grep -v 'bash -c' | awk '{print $2}'`
    
    for pid in $pids;
    do
        kill $pid;
        echo "$PROGNAME($pid) is stopping, please waiting"
        iCnt=1
        while [ $iCnt -le 5 ]
        do
            let iCnt++
            sleep 2
            exist
            if [ $? -eq 0 ]; then
              let iCnt+=15
              echo "$PROGNAME($pid) is stopped"
            else
              echo "【WARN】$PROGNAME($pid) is stop fail"
            fi
        done
    done
}


case "$optype" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo "Only support start|stop|restart"
        exit 1
esac